<template>
  <div>
    <el-form ref="form" :model="form" :rules="rules" label-width="120px">
      <el-form-item label="可读的应用">
        <el-checkbox-group v-model="allow_app_read">
          <el-checkbox v-for="i in app" :label="i.id" :key="i.id">{{i.name}}</el-checkbox>
        </el-checkbox-group>
      </el-form-item>
      <el-form-item label="唯一标识" prop="action">
        <el-input class="w500" v-model="form.action" placeholder="例如：sendSms"></el-input>
      </el-form-item>
      <el-form-item label="描述" prop="description">
        <el-input class="w500" type="textarea" v-model="form.description" :rows="5"></el-input>
      </el-form-item>
      <el-form-item label="模版" >
        <el-input class="w500" type="textarea" v-model="form.sms_info.text" :rows="5"></el-input>
      </el-form-item>
      <el-form-item label="apikey" prop="apikey">
        <el-input class="w500" v-model="form.sms_info.apikey" ></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSubmit('form')">提交</el-button>
        <el-button @click="goBack">返回</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
  import { mapState } from 'vuex'
  import notify from '@/tools/notify'

  export default {
    data: function () {
      return {
        allow_app_read: [],
        rules: {
          rules: {
            action: [
              {required: true, message: '请输入标识', trigger: 'blur'}
            ]
          }
        }
      }
    },
    computed: {
      ...mapState({
        app: state => state.app.all,
        form: state => state.sms.smsInfo
      })
    },
    async created () {
      await this.smsInfo()
      await this.appAll()
      let arr = this.form.other_app_read.split(',')
      for (let i = 0; i < arr.length; i++) {
        arr[i] = Number(arr[i])
      }
      this.allow_app_read = arr
    },
    methods: {
      // 获取短信配置信息
      async smsInfo () {
        let payload = {
          id: this.$route.params.id
        }
        await this.$store.dispatch('sms/smsInfo', payload)
      },
      // 获取不分页的应用列表
      async appAll () {
        await this.$store.dispatch('app/appAll')
      },
      onSubmit (formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            this.form.other_app_read = this.allow_app_read.join(',')
            this.$store.dispatch('sms/smsEdit', this.form).then(res => {
              notify.success(res.msg)
              this.$router.push('/sms/list')
            })
          }
        })
      },
      goBack () {
        this.$router.go(-1)
      }
    }
  }
</script>
